

export default {
  
  namespaced: true,
  
  state: () => ({
    cart: JSON.parse( uni.getStorageSync('cart') || '[]' )
  }),
  
  mutations: {
    
    addToCart(state, goods){
      console.log('添加商品到购物车', goods)
      // console.log(state.cart)
      const result = state.cart.find((item) => {
        return item.goods_id === goods.goods_id
      })
      if(!result){
        state.cart.unshift(goods)
      }else{
        result.goods_count = result.goods_count + 1
      }
      // console.log(state.cart)
      
      // 保存到本地
      this.commit('m_cart/saveToStorage')
      
    },
    
    // 更新购物车选中状态
    updateGoodsState(state, goods){
      const result = state.cart.find(item => item.goods_id === goods.goods_id)
      if(result){
        result.goods_state = goods.goods_state
      }
      
      // 保存到本地
      this.commit('m_cart/saveToStorage')
    },
    
    // 更新购物车商品数量
    updateGoodsCount(state, goods){
      const result = state.cart.find(item => item.goods_id === goods.goods_id)
      if(result){
        result.goods_count = goods.goods_count
      }
      
      // 保存到本地
      this.commit('m_cart/saveToStorage')
    },
    
    // 全选/反选
    updateAllGoodsState(state, newState){
      state.cart.forEach(item => item.goods_state = newState)
      
      // 保存到本地
      this.commit('m_cart/saveToStorage')
    },
    
    // 保存购物车信息到本地
    saveToStorage(state){
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    }
  },
  
  getters: {
    total(state) {
      let c = 0
      state.cart.forEach(item => {
        c += item.goods_count
      })
      return c
    },
    checkedCount(state) {
      return state.cart.filter(item =>item.goods_state).reduce((total, curr) => total += curr.goods_count, 0)
    },
    
    // 价格计算
    checkedGoodsAmount(state){
      return state.cart.filter(item => item.goods_state)
                       .reduce((total, curr) => total += curr.goods_price * curr.goods_count , 0)
                       .toFixed(2)
    }
  }
  
}